﻿using System;
using System.Text;
using System.Text.Json;

namespace Loong.Json
{
    public static class JsonExtensions
    {
        public static string ToJsonString(this object obj)
        {
            return JsonSerializer.Serialize(obj, obj.GetType());
        }

        public static object FromJsonString(this string value, Type returnType)
        {
            return JsonSerializer.Deserialize(value, returnType);
        }

        public static T FromJsonString<T>(this string value)
        {
            return JsonSerializer.Deserialize<T>(value);
        }

        public static string GetJsonKeyValue(this string json, string key)
        {
            int keyIndex = json.IndexOf(key);
            if (keyIndex == -1)
            {
                return string.Empty;
            }

            while (json[keyIndex - 1] != '"' || json[keyIndex + key.Length] != '"')
            {
                keyIndex = json.IndexOf(key, keyIndex + 1);
                if (keyIndex == -1)
                {
                    return string.Empty;
                }
            }

            int length = key.Length;
            int valueIndex = keyIndex + length + 2;
            char valueFirstChar = json[valueIndex];
            if (valueFirstChar == '{')
            {
                return GetObjectValue(valueIndex, json);
            }
            if (valueFirstChar == '"')
            {
                return GetStringValue(valueIndex, json);
            }

            return string.Empty;
        }

        private static string GetObjectValue(int index, string json)
        {
            int num = 0;
            StringBuilder stringBuilder = new StringBuilder();
            char ch;
            while (true)
            {
                ch = json[index];
                if (ch == '{')
                {
                    ++num;
                }
                if (ch == '}')
                {
                    --num;
                }
                if (num != 0)
                {
                    stringBuilder.Append(ch);
                    ++index;
                }
                else
                {
                    break;
                }
            }
            stringBuilder.Append(ch);
            return stringBuilder.ToString();
        }

        private static string GetStringValue(int index, string json)
        {
            StringBuilder stringBuilder = new StringBuilder();
            ++index;
            while (true)
            {
                char ch = json[index++];
                if (ch != '"')
                {
                    stringBuilder.Append(ch);
                }
                else
                {
                    break;
                }
            }
            return stringBuilder.ToString();
        }
    }
}
